package cn.dakaqi.open.maibao;

import cn.dakaqi.annotation.EncryptionParam;
import cn.dakaqi.entities.*;
import cn.dakaqi.entities.user.User;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.entities.user.VolunteerInsurance;
import cn.dakaqi.exception.MaibaoParamException;
import cn.dakaqi.services.*;
import cn.dakaqi.services.user.UserService;
import cn.dakaqi.services.user.VolunteerInsuranceService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.UUIDHexGenerator;
import cn.dakaqi.vo.request.openPlatform.*;
import cn.dakaqi.vo.response.DataResponseVo;
import cn.dakaqi.vo.response.UserVolunteer;
import com.wordnik.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.web.MediaTypes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by chunyang on 2016/4/7.
 * 用户
 */
@RestController
@RequestMapping(value = "/api/v1/open")
@Slf4j
@Api(value = "脉保API")
public class OpenController {

    @Autowired
    PinganOpenService pinganOpenService;
    @Resource
    private PinganInsuranceService pinganInsuranceService;
    @Resource
    private ActivitySignRecordService activitySignRecordService;
    @Resource
    private ActivityApplyService activityApplyService;
    @Resource
    private GroupVolunteerService groupVolunteerService;
    @Resource
    private UserService userService;
    @Resource
    private ActivityService activityService;
    @Resource
    private GroupService groupService;
    @Resource
    private VolunteerService volunteerService;
    @Resource
    private VolunteerInsuranceService volunteerInsuranceService;
    @Resource
    private CustomerService customerService;
    @Autowired
    ConfigUtil configUtil;

    //用户注册
    @RequestMapping(value = "/createUser", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8, consumes = "application/json")
    public DataResponseVo<UserVolunteer> createUserOpen(@RequestBody UserVo param) {
        UserVolunteer userVolunteer = createUser(param);

        Volunteer volunteer = userVolunteer.getVolunteer();
        volunteer.setRealName(param.getName());
        volunteer.setCardNO(param.getIdCard());
        volunteer.setCardType("CID");
        volunteer.setMobile(param.getMobile());
        volunteer.setBirthDay(param.getIdCard().substring(6, 10) + "-" + param.getIdCard().substring(10, 12) + "-" + param.getIdCard().substring(12, 14));
        volunteerService.updateVolunteer(volunteer);
        return new DataResponseVo<>(0, "", userVolunteer);
    }

    /**
     * 创建社团
     * @param param 用户输入参数
     * @return 创建的社团
     */
    @RequestMapping(value = "/createGroup", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8, consumes = MediaTypes.JSON_UTF_8)
    public DataResponseVo<Group> createGroup(@RequestBody GroupVo param) {

        Volunteer volunteer = volunteerService.findByMemberCode(param.getMemberCode());
        Group group = new Group();
        group.setName(param.getName());
        group.setLogo(param.getLogo());
        group.setDemo(param.getDemo());
        group.setServiceField(param.getServiceField());
        group.setSetupDate(param.getSetupDate());
        group.setRegAddress(param.getRegAddress());
        group.setMonitor(volunteer.getRealName());
        group.setPhone(volunteer.getMobile());
        group.setCreateUser(volunteer);
        group.setProvince(param.getPrvoince());
        group.setCity(param.getCity());
        group.setDistrict(param.getDistrict());
        group = groupService.save(group);
        return new DataResponseVo<>(0, "", group);
    }

    /**
     * 领取保险
     * @return 保险信息
     */
    @RequestMapping(value = "/maibao", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8, consumes = "application/json")
    @EncryptionParam
    public DataResponseVo<Object> maibao(HttpServletRequest request) {
        if (request.getSession().getAttribute("jsonParam") == null) {
            throw new MaibaoParamException("1", "获取参数失败！");
        }
        String jsonParam = request.getSession().getAttribute("jsonParam").toString();
        System.out.println("第三步---3---" + jsonParam + "--------");
        MaibaoVo maibaoVo = MaibaoVo.build(jsonParam);


        request.getSession().removeAttribute("jsonParam");

        if (maibaoVo.getIdCard() == null || maibaoVo.getIdCard().length() != 18) {
            throw new MaibaoParamException("1", "身份证号码不合法！");
        }
        if (maibaoVo.getName() == null) {
            throw new MaibaoParamException("1", "投保人姓名不能为空！");
        }
        if (maibaoVo.getMobile() == null) {
            throw new MaibaoParamException("1", "手机号码不能为空！");
        }
        if (maibaoVo.getActivityName() == null) {
            maibaoVo.setActivityName("公益活动！");
        }

        //时间校验
        if (maibaoVo.getStartTime() == null || maibaoVo.getEndTime() == null) {
            throw new MaibaoParamException("1", "投保时间不能为空！");
        }

        //获取第三方用户信息
        Customer customer = customerService.findByCode(maibaoVo.getCustomerCode());
        //组织code
        String groupCode = customer.getGroupCode();

        UserVo paramUser = UserVo.build(maibaoVo);
        //默认密码6位生日
        paramUser.setPassword(maibaoVo.getIdCard().substring(8, 13));

        ActivityVo paramActivityCreate = ActivityVo.build(maibaoVo);

        ActivityVo joinActivityParam = ActivityVo.build(maibaoVo);

        RecordVo recordVo = new RecordVo();

        PinganOpen pinganOpenParam = new PinganOpen();
        pinganOpenParam.setMobile(maibaoVo.getMobile());
        pinganOpenParam.setSn(maibaoVo.getSn());
        pinganOpenParam.setStatus(maibaoVo.getStatus());
        pinganOpenParam.setActivateSn(maibaoVo.getActivateSn());
        pinganOpenParam.setActivateTime(maibaoVo.getActivateTime());
        pinganOpenParam.setCardNum(maibaoVo.getCardNum());
        pinganOpenParam.setCreateTime(maibaoVo.getCreateTime());
        pinganOpenParam.setGuardianIDCard(maibaoVo.getGuardianIDCard());
        pinganOpenParam.setGuardianMobile(maibaoVo.getGuardianMobile());
        pinganOpenParam.setGuardianName(maibaoVo.getGuardianName());
        pinganOpenParam.setPlatform(maibaoVo.getPlatform() + "");
        pinganOpenParam.setName(maibaoVo.getName());
        pinganOpenParam.setIdCard(maibaoVo.getIdCard());


        UserVolunteer userVolunteer;
        Volunteer volunteer;
        User user = userService.findByMobile(maibaoVo.getMobile());
        if (user == null) {
            //创建用户
            userVolunteer = createUser(paramUser);//create user

            volunteer = userVolunteer.getVolunteer();
            volunteer.setActs(0);
            volunteer.setRank(0);
            volunteer.setRealName(maibaoVo.getName());
            volunteer.setCardNO(maibaoVo.getIdCard());
            volunteer.setCardType("CID");
            volunteer.setMobile(maibaoVo.getMobile());
            volunteer.setBirthDay(maibaoVo.getIdCard().substring(6, 10) + "-" + maibaoVo.getIdCard().substring(10, 12) + "-" + maibaoVo.getIdCard().substring(12, 14));
            volunteerService.updateVolunteer(volunteer);
        } else {
            volunteer = volunteerService.findByUserId(user.getId());
        }

        String memberCode = volunteer.getMemberCode();

        //判断用户是否已经加入该组织
        GroupVolunteer groupVolunteer = groupVolunteerService.findByMemberAndGroup(volunteer.getMemberCode(), DKQConstant.APPLY_STATUS_OK, groupCode);

        if (groupVolunteer == null) {
            //加入组织
            groupVolunteer = joinGroup(groupCode, memberCode);//join group
            //审核通过
            groupVolunteerService.updateStatus(groupVolunteer.getId(), DKQConstant.APPLY_STATUS_OK, customer.getMemberCode(), "");
        }


        volunteer = volunteerService.findOne(volunteer.getId());

        //创建活动
        Activity activity = activityService.findByTime(paramActivityCreate.getStartTime(), paramActivityCreate.getEndTime());
        if (null == activity) {//如果开始时间结束时间相同的活动已存在 则不再创建新的活动
            paramActivityCreate.setCrateUseMemberCode(customer.getMemberCode());
            paramActivityCreate.setMonitorMemberCode(customer.getMemberCode());
            paramActivityCreate.setType(Activity.TYPE_1);
            paramActivityCreate.setGroupCode(groupCode);
            List<Activity> activityList = createActivity(paramActivityCreate);//createActivity
            activity = activityList.get(0);
        }

        ActivityApply activityApply = activityApplyService.findByVolunteerAndActivity(memberCode, activity.getActivityCode());
        if (activityApply == null) {
            //加入活动
            joinActivityParam.setRole(DKQConstant.ROLES_VOLUNTEER);
            joinActivityParam.setMemberCode(memberCode);
            joinActivityParam.setActivityCode(activity.getActivityCode());
            joinActivity(joinActivityParam);
        }

        //打卡记录
        recordVo.setLat(paramActivityCreate.getLat());
        recordVo.setLng(paramActivityCreate.getLng());
        recordVo.setActivityCode(activity.getActivityCode());
        recordVo.setMemberCode(memberCode);
        recordVo.setCreateTime(activity.getCreateTime());
        createRecord(recordVo);

        VolunteerInsurance volunteerInsurance = volunteerInsuranceService.findByVolunteerCode(volunteer.getVolunteerCode());
        if (volunteerInsurance == null) {
            //买保险
            pinganOpenParam.setMemberCode(memberCode);
            pinganOpenParam.setVolunteerCode(volunteer.getVolunteerCode());
            JsonResult jsonResult = createInsurance(pinganOpenParam);
            if (jsonResult.getCode() == JsonResult.CODE_FAIL) {
                return new DataResponseVo<>(2, "购买失败！");
            }

//                volunteerInsurance = volunteerInsuranceService.findByVolunteerCode(volunteer.getVolunteerCode());

            //******测试环境---仅供测试使用--开始******
            volunteerInsurance = volunteerInsuranceService.findByVolunteerCode("31-00000207-0");
            if(volunteerInsurance==null){
                return new DataResponseVo<>(2, "基础数据丢失！");
            }
            volunteerInsurance.setInsuranceNo(UUIDHexGenerator.generator());
            //******测试环境---仅供测试使用--结束******
        } else {
            return new DataResponseVo<>(3, "该用户已经购买过了！", volunteerInsurance);
        }
        return new DataResponseVo<>(0, "购买成功！", volunteerInsurance);
    }

    //加入组织
    private GroupVolunteer joinGroup(String groupCode, String memberCode) {

        GroupVolunteer groupVolunteer = new GroupVolunteer();
        Group group = groupService.findByGroupCode(groupCode);
        Volunteer volunteer = volunteerService.findByMemberCode(memberCode);

//        if (!Volunteer.checkInfo(volunteer)) {
//            return new DataResponseVo<>(-1109, "请完善个人资料");
////            throw new ServiceRuntimeException(ErrorCodeMsg.USER_INFO_NOT_FULL);
//        }
        groupVolunteer.setVolunteer(volunteer);
        groupVolunteer.setGroup(group);
        groupVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
        groupVolunteer.setRole(DKQConstant.ROLES_VOLUNTEER);
        groupVolunteer.setStatus(DKQConstant.APPLY_STATUS);

        groupVolunteer = groupVolunteerService.save(groupVolunteer);
        return groupVolunteer;
    }

    //用户注册
    private UserVolunteer createUser(UserVo param) {

        User user = new User();
        user.setMobile(param.getMobile());
        user.setPassword(param.getPassword());
        user.setRealName(param.getMobile());
        user.setNickName(param.getMobile());
        user.setRoles("user");
        user.setEmail(param.getMobile() + "@dakaqi.cn");
        user.setPlatform(param.getPlatform());
        user.setArea(param.getArea());
        user.setLng(param.getLng());
        user.setLat(param.getLat());
        user.setClient(ConfigUtil.getClientId());
        return userService.saveUser(user, "dakaqiCode");
    }

    //创建活动
    private List<Activity> createActivity(ActivityVo param) {
        Volunteer volunteerCreateUser;

        Activity activity = new Activity();

        Volunteer volunteerMonitor = volunteerService.findByMemberCode(param.getMonitorMemberCode());
        if (!param.getMonitorMemberCode().equals(param.getCrateUseMemberCode())) {
            volunteerCreateUser = volunteerService.findByMemberCode(param.getCrateUseMemberCode());
        } else {
            volunteerCreateUser = volunteerMonitor;
        }
        Group group = this.groupService.findByGroupCode(param.getGroupCode());
        activity.setGroup(group);
        activity.setGroup(group);
        activity.setCreateUser(volunteerCreateUser);
        activity.setMonitor(volunteerMonitor);
        activity.setSkill(param.getSkill());
        activity.setScope(param.getScope());
        activity.setNeeds(param.getNeeds());
        activity.setName(param.getName());
        activity.setDemo(param.getDemo());
        activity.setImgs(param.getImgs());
        activity.setType(param.getType());
        activity.setStartTime(param.getStartTime());
        activity.setEndTime(param.getEndTime());
        activity.setAddress(param.getAddress());
        activity.setTags(param.getTags());
        activity.setWeekDay(param.getWeekDay());
        activity.setProvince(param.getProvince());
        activity.setCity(param.getCity());
        activity.setDistrict(param.getDistrict());
        activity.setLng(param.getLng());
        activity.setLat(param.getLat());
        activity.setActStatus(DKQConstant.ACT_STATUS_OUTER);
        activity.setClient(ConfigUtil.getClientId());
        activity.setDemo("不限制");
        activity.setTags("保险");
        activity.setSkill("不限制");
        //        return new ListDataResponseVo<>(0, "", activityList);
        return activityService.save(activity);
    }

    private ActivityApply joinActivity(@RequestBody ActivityVo param) {
        Volunteer volunteer = volunteerService.findByMemberCode(param.getMemberCode());

        ActivityApply activityApply = new ActivityApply();
        activityApply.setCreateTime(Clock.DEFAULT.getCurrentDate());
        activityApply.setVolunteer(volunteer);
        activityApply.setActivity(activityService.findByActivityCode(param.getActivityCode()));
        activityApply.setRole(param.getRole());
        activityApply.setStatus(DKQConstant.APPLY_STATUS_OK);
        activityApply = activityApplyService.save(activityApply);
//        return new DataResponseVo<>(0, "", activityApply);
        return activityApply;
    }

    private void createRecord(@RequestBody RecordVo param) {
        Volunteer volunteer = volunteerService.findByMemberCode(param.getMemberCode());
        Activity activity = activityService.findByActivityCode(param.getActivityCode());
        ActivitySignRecord activitySignRecord = new ActivitySignRecord();
        activitySignRecord.setVolunteer(volunteer);
        activitySignRecord.setActivity(activity);
        activitySignRecord.setCreateTime(param.getCreateTime());
        activitySignRecord.setLng(param.getLng());
        activitySignRecord.setLat(param.getLat());
        activitySignRecord.setAdress("默认地址");

        ActivitySignRecord lstSignRecord = new ActivitySignRecord();
        lstSignRecord.setVolunteer(volunteer);
        lstSignRecord.setActivity(activity);
        lstSignRecord.setCreateTime(param.getCreateTime());
        lstSignRecord.setLng(param.getLng());
        lstSignRecord.setLat(param.getLat());
        lstSignRecord.setAdress("默认地址");

        activitySignRecordService.saveMaibao(activitySignRecord,lstSignRecord);
    }

    //简单的领取保险
    @RequestMapping(value = "/simple", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> getINSURANCE(@RequestParam(value = "customerCode", required = true) String customerCode,@RequestParam("mobile") String mobile,@RequestParam("name") String name,@RequestParam("idCard") String idCard)
    {
        JsonResult jsonResult = new JsonResult();

        Customer customer = customerService.findByCode(customerCode);
        if(null == customer)
        {
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage("未授权,不可以操作");
            return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
        }
        //更新当前身份证用户的一号通和MEMBERCODE
        Volunteer volunteer = volunteerService.findByCardNO(idCard);
        if(null == volunteer)
        {
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage("非注册志愿者,不可以领取保险");
            return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
        }
        PinganOpen pinganOpen = pinganOpenService.findByIdCard(idCard);
        if(null == pinganOpen)
        {
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage("非注册志愿者,不可以领取保险");
            return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
        }
        pinganOpen.setVolunteerCode(volunteer.getVolunteerCode());
        pinganOpen.setMemberCode(volunteer.getMemberCode());
        this.pinganOpenService.save(pinganOpen);

        pinganInsuranceService.createInsurance(pinganOpen);
        jsonResult.setCode(JsonResult.CODE_SUCCESS);
        jsonResult.setMessage("保险领取成功");
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }
    private JsonResult createInsurance(PinganOpen param) {
        //        return new DataResponseVo<>(0, "", volunteerInsurance);
        return pinganInsuranceService.createInsurance(param);
    }




    @RequestMapping(value="/test")
    public Customer test(String string) throws Exception {

        throw new Exception("test Error");

    }
}








